//-------------------------------------------------------------------------------------------------
// author zhangwei on 2015.08.10
// modified by zhangwei on 2015.08.10
// - Released ver v1. This version is the clone from: https://github.com/TahaSh/Tasks-App-With-VueJS
//   And there's a good article about it: http://taha-sh.com/blog/many-js-frameworks-but-vuejs-is-different 
// modified by zhangwei on 2015.08.10
// - Released ver 2. This is a readonly list.
// modified by zhangwei on 2015.08.28
// - Add grid component.
// modified by zhangwei on 2015.09
// - Add div switch to edit mode and setMode() support.
//
// Reference
// - http://taha-sh.com/blog/many-js-frameworks-but-vuejs-is-different
// - Html5's <template>, http://www.zhangxinxu.com/wordpress/2014/07/hello-html5-template-tag/
//
//-------------------------------------------------------------------------------------------------


// TODO on 2015.08.23
// - Uses vue-resource to fetch data from the backend or jQuery ajax to communicate with backend service.
// - Suggest use the standard code pattern in vue grid/table examples. 
//   Better encapsulate the table as a component.


Array.removeRange = function(array, from, to) {
    var rest = array.slice((to || from) + 1 || array.length);
    array.length = from < 0 ? array.length + from : from;
    return array.push.apply(array, rest);
};

function removeAt(array,idx)  
{  
        if(! Array.prototype.isPrototypeOf(array)){  
            return null;//根据Null可以判断本次调用失败  
        }  
        var idx = parseInt(idx),  
            iLen = idx.length;  
        if(idx < 0 || idx >= iLen){  
            return null;//根据Null可以判断本次调用失败  
        }  
        var aRet = [];//与NULL不同  
        return aRet=array.slice(0,idx).concat(array.slice(idx+1));  
}  

/*
    VueUI.resetArray = function (a, b){
        while (a.length){
            a.pop()
        }
        b.forEach(function (x){
            a.push(x)
        })
    }
*/


// Application Service Used by the Vue Layer(View Layer)
var AppService = {

	urlroot: "http://192.168.130.140:8080/site/mvc/members/",

	init: function(){
		//Vue.http.options.root = '/root';
		Vue.http.options.root = this.urlroot;
		//Vue.http.headers.common['Authorization'] = 'Basic YXBpOnBhc3N3b3Jk';	
	},
	
	newItem: function(){
		return newItem(1, true);
	},

	newItem: function(newid, newselected){ 
		var item = {
			id:newid, 
			rowid: 3, 
			node: '3211', 
			selected: newselected,
			name:"zhang san",
			gender:true, 
			email: "zhagnsan@163.com", 
			mobilephone:"1373214421", 
			timestamp: '2015.07.08Z23:12:56:324:313', 
			frame: '56 7F 2A 3D', 
			title: 'Go to grocery store', 
			completed: false 
		};
		return item;
	},
	
	/*
	find: function(inputQuery, pagenum, pagesteps, items, options){
		//items.splice(0, items.length);
		items.length = 0;
		for (var i=0; i<pagesteps; i++)
		{
			items.push(this.newItem(pagenum*pagesteps + i, (i % 2 == 0)));
		}
	},
	*/
		
	// success(data, status, request)
	// error(data, status, request)
	find: function(inputQuery, pagenum, pagesteps, items, success_callback, error_callback){
		//items.splice(0, items.length);
		items.length = 0;
		Vue.http.get(this.urlroot, success_callback).error(error_callback);
		/*
			$.ajax({
				context: this,
				url: "/rest/istream",
                success: function (result) {
                	this.$set("items", result) 
                }
            })
		*/
	},

	/*
	_find: function(inputQuery, pagenum, pagesteps, callback){
		var items = [];
		for (var i=0; i<pagesteps; i++)
		{
			items.push(this.newItem(i, (i % 2 == 0)));
		}
		
		if (typeof callabck == "function")
			callback(items);
	},
	
	load: function(ctx, succ_callback, fail_callback) {
		$.ajax({
			context: ctx,
			url: "/rest/istream",
                success: function (result) {
                	succ_callback(result)
                }
        })
    },
	*/
	
	get: function(id){
	},
	
	get: function(items, id){
		var result = null;
		var i = items.length;
		while (i--) {
			if (items[i].id == id)
			{
				result = items[i];
				break;
			}
		}
		return result;
	},	

	indexof: function(items, id){
		var idx = null;
		var i = items.length;
		while (i--) {
			if (items[i].id == id)
			{
				idx = i;
				break;
			}
		}
		return i;
	},	

	set: function(id, item){
			$.ajax({
				context: item,
                type: "DELETE",
                url: "/rest/inputstream/" + item.id,
            })
	},

	add: function(item){
	/*
			$.ajax({
				context: this,
                type: "POST",
                data: {
                	//item：this.item,
					//author: this.author,
                    text: this.text
                },
                url: urlroot,
				success: function(result) {
					this.items.push(result);
                    this.author = ''
                    this.text = ''
                    }
                })                        
            },
				*/
	},
	
    remove: function(item){
		return null;
	/*
			$.ajax({
				context: '', //item,
                type: "DELETE",
                url: urlroot + id,
            });
	*/
    }
};


var svc = Object.create(AppService);

Vue.component('child', {
  props: ['myMessage'],
  template: '<span>通信录标题测试 <small>{{myMessage}}</small></span>'
});

// register modal component
Vue.component('itemeditor', {
	template: '#itemeditor-tpl',
	
	// item: {
	//		id: String,
	//		gender: Boolean,
	//		name: String,
	//		selected: true
	// }
	
	props:[
		{
			name: 'item', 
			type: Object,
			twoWay: false,
			required: true
		},
		{
			name: 'mode',
			type: String,
		},
		{
			name: 'onSubmit',
			type: Function,
			required: true,
		},
		{
			name: 'onCancel',
			type: Function,
		},
	],

	data: function () {
        return {
			result: ''
        }
    },
	
	methods: {
		onSubmitClick: function(e){	
			console.log("onSubmitClick: inside component itemeditor");
			this.result = this.onSubmit(this.mode, this.item);
		},
		onCancelClick: function(e){
			console.log("onCancelClick: inside component itemeditor");
			this.onCancel(this.mode, this.item);
		},
	},
	
	ready: function () {
		// this.onLoad('message from child!')
	}
});

// register modal component
Vue.component('modal', {
	template: '#modal-template',
	props: {
		show: {
			type: Boolean,
			required: true,
			twoWay: true    
		},
	}
});

var vm = new Vue({
    el: '#app',
	
	data: {
		currentView: 'itemeditor',
		begintime: '',
		endtime: '',
		remotedevice: '',
		searchQuery: '',
		items: [],
		curitem: {},
		selectall: true,
		showModal: false,
		mode: 'modeList', // modeList, modeItemView, modeAddNew, modeEdit
		modeTitle: "",
		parentMsg: "test",
	},
	
	components: {
		//list: { /* ... */ },
		//itemviewer: { /* ... */ },
		//itemeditor: itemeditor,
	},
	
	methods: {
		/*
		init: function(){
			svc.init();
			svc.find1('', 1, 7, this.items, {});
			if (this.items.length > 0)
			{
				this.$set("curitem", this.items[0]);
			}
		},
		*/
		
		init: function(){
			svc.init();
			
			//var inputQuery = '';
			// basicsearch(inputQuery);
			
			svc.find('', 1, 7, this.items, function(data, status, request){
				var i = data.length;
				while (i--)
				{
					data[i].rowid = i,
					data[i].node = '3211', 
					data[i].selected = (i % 2);
					data[i].name = "zhang san",
					data[i].gender = true, 
					data[i].email = "zhagnsan@163.com", 
					data[i].mobilephone = "1373214421", 
					data[i].timestamp = '2015.07.08Z23:12:56:324:313', 
					data[i].frame = '56 7F 2A 3D', 
					data[i].title = 'Go to grocery store', 
					data[i].completed = false
				}
				this.$set('items', data)
				if (this.items.length > 0)
				{
					this.$set("curitem", this.items[0]);
				}
				alert("init: items.length = " + this.items.length);
			}, function (data, status, request) {
				alert("method search: fetch data from backend server failed! ");
				alert(data + ' ' + status + ' ' + request);
			});
		},
		
		basicsearch: function(inputQuery){
			// svc.find(inputQuery, 2, 5, this.items, {});

			svc.find('', 1, 7, this.items, function(data, status, request){
				var i = data.length;
				while (i--)
				{
					data[i].rowid = i,
					data[i].node = '3211', 
					data[i].selected = (i % 2);
					data[i].name = "zhang san",
					data[i].gender = true, 
					data[i].email = "zhagnsan@163.com", 
					data[i].mobilephone = "1373214421", 
					data[i].timestamp = '2015.07.08Z23:12:56:324:313', 
					data[i].frame = '56 7F 2A 3D', 
					data[i].title = 'Go to grocery store', 
					data[i].completed = false
				}
				this.$set('items', data)
				if (this.items.length > 0)
				{
					this.$set("curitem", this.items[0]);
				}
				alert("init: items.length = " + this.items.length);
			}, function (data, status, request) {
				alert("method search: fetch data from backend server failed! ");
				alert(data + ' ' + status + ' ' + request);
			});
		},
				
		advancedsearch: function(e){
			console.log("search button");
			console.log(e.target.tagName); // "BUTTON"
			console.log(e.targetVM === this); // true
			
			this.searchQuery = this.searchQuery.trim();
			if ((this.searchQuery).length == 0 ) 
			{ 
				document.getElementById("searchQuery").focus(); 
				alert("Please input search query"); 
			} 

			var inputs = new Array();
			inputs[0] = "{begintime:'";
			inputs[1] = this.begintime;
			inputs[2] = "', endtime:'";
			inputs[3] = this.endtime;
			inputs[4] = "', remotedevice:'";
			inputs[5] = this.remotedevice;
			inputs[6] = "', searchQuery:'";
			inputs[7] = this.searchQuery;
			inputs[8] = "'}";
			inputQuery = inputs.join('');
			
			console.log("your input query condition is " + inputQuery);
			
			basicsearch(inputQuery);
		},

		/*
		_findxxx: function(vm, inputQuery, pagenumber, pagesteps){
			setTimeout(function(){
				svc.find(inputQuery, 1, 6, function(data){
					vm.$set('items', data);
				});
			}, 50);
		    setTimeout(function (){
				var data =  svc.find(pagenumber, pagesteps);
				var tmplen = vm.items.length;
				for (var i=0; i<pagesteps; i++)
				{
					data[i].rowid = tmplen + i;
					//vm.items.push(data[i]);
				}
				vm.$set('items', data);
		    }, 100)
		},

        // TODO: test with backend
		onFetchItems: function() {
			$.ajax({
				context: this,
				url: "/rest/istream",
                success: function (result) {
                	this.$set("items", result) 
                }
            })
        },
		*/

		/*
		onFetchItems2: function() {
			svc.load(this, function(result){
				this.$set("items", result) 
			}, null);
        },

        clearData : function (){
			console.log("clear button");
            var myTable = VueUI.getComponent('myTable')
            VueUI.resetArray(tableConf.data, [])
            //tableConf.data = []
            //tableConf.data = []
            //myTable.data = []	
            myTable.totalPage = 0
            myTable.totalCount = 0
        }
		*/

		onSave: function(mode,item){
			alert("inside method save()");
			console.log("save");
			console.log(mode);
			console.log(item);
			if (mode == 'modeAddNew')
			{
				svc.add(item);
				// TODO
				this.items.push(item);
			}
			else{
				svc.set(item.id, item);
				var idx = svc.indexof(this.items, item.id);
				if (idx != null)
				{
					vm.$set(this.items[idx], item);
				}
			}
			
			this.mode = 'modeList';
			// this.curitem = item;
			return "success";
		},
		
		onCancel: function(mode,item){
			alert("inside onCancel");
			console.log("onCancel");
			console.log(mode);
			console.log(item);
			this.mode = 'modeList';
		},
		
		//sortBy: function (key) {
		//	this.sortKey = key
		//	this.reversed[key] = !this.reversed[key]
		//}

        // TODO: test with backend
  		onEdit: function(item, e){
  			console.log('editItem ' + item);
			setMode('modeEdit');
            // this.showModal=true;
  		},

        // TODO: test with backend
  		onRemoveItem: function(item, e){
  			console.log('removeItem' + item);
			svc.remove(item);
            this.items.$remove(item);
  		},

		// delete each item according to the item.selected property
		onRemoveSelected: function(e){
			console.log("removeSelected: " + e);
			var items = this.items;
			for (var i in items){
				if (items[i].selected)
				{
					console.log(items[i] + ' is to be deleted!!!');
					this.onRemoveItem(items[i], null);
				}
			}
		},
		
		setMode: function(newmode){
			if (this.mode != newmode)
			{
				this.mode = newmode;
				switch (newmode)
				{
				case "modeList":
					this.modeTitle = "";
					break;
				case "modeItemView":
					this.modeTitle = " [详情]";
					break;
				case "modeEdit":
					this.modeTitle = " [编辑]";
					break;
				case "modeAddNew":
					this.modeTitle = " [新增]";
					break;
				default:
					this.modeTitle = "";
				}
			}
		},
	},
	
	ready: function(){
		// console.log("ready function is called");
	}
});

setTimeout(function (){
	vm.init();
}, 50);

// equvalent to $(document).ready(function(){...}
$(function () {
});
  


